<script>
	import {
		baseURL
	} from '@/config'
	import Voice from '@/libs/QS-baiduyy.js'
	import placeMap from '@/libs/place-map.js'
	import permission from '@/libs/permission.js' //权限插件
	import APPUpdate from "@/components/APPUpdate/index.js"
	import AudioPlayer from 'untils/audio-player.js'; //播放 
	import {
		get_property_list_by_type,
		getDeviceInfo,
		// getAppList,
		// getContacts,
		isResidueTimeByMinute,
	} from '@/libs/unit.js'
	import sqlite from '@/libs/sqlite/chatSqlite.js'
	import Base64 from "base-64";
	export default {
		globalData: {
			isLogin: false // 用户是否已登录
		},
		data() {
			return {
				workTimes: null, //定时器，开工校验
				app_volume: '', //app内的最低音量
				isZdyV: 0
			}
		},
		onShow() {
			// 获取七牛上传TOKEN
			if (!uni.getStorageSync('uploadToken') && uni.getStorageSync('token')) {
				let res5 = this.$fetch(this.$api.get_qiniu_token, {}, 'POST')
				console.log(res5, 'hello')
				uni.setStorageSync('uploadToken', res5.msg)
			}
		},
		// 页面加载时触发 
		onLaunch: function() {
			try {
				const oMeta = document.createElement('meta');
				oMeta.name = "referrer";
				oMeta.content = "no-referrer"
				document.getElementsByTagName('head')[0].appendChild(oMeta);
				plus.screen.lockOrientation('landscape-primary'); //锁定横屏
				plus.navigator.setFullscreen(true); //隐藏状态栏(应用全屏:只能隐藏状态栏，标题栏和虚拟返回键都还可以显示)		
			} catch (e) {
				console.log('没有document')
			}
			// 获取系统信息
			const systemInfo = uni.getSystemInfoSync();
			// 应用程序版本号
			const version = systemInfo.version
			uni.setStorageSync('versionSy', version)
			uni.hideTabBar()
			console.log('App Launch');
			if (uni.getStorageSync('token')) {
				setInterval(() => {
					this.refreshLocation()
				}, 600000)
			}
			// #ifdef APP-PLUS
			uni.$on('userLogin', () => {
				if (uni.getStorageSync('token')) {
					console.log('用户登录了-----', uni.getStorageSync('token'))
					if (!this.globalData.isLogin) {
						this.globalData.isLogin = true
						this.initDB()
					}
				} else {
					console.log('用户未登录-----')
					this.globalData.isLogin = false
					uni.closeSocket()
					sqlite.closeSQL()
				}
			})
			// #endif
			//设置app有声音
			// if (!uni.getStorageSync('checked1')) {
			// 	uni.setStorageSync('checked1', true)
			// }
			// console.log('App Launch声音~~~~', uni.getStorageSync('isVoice'))
			this.handleData() //数据处理,配置数据
			this.setTabr() // 根据用户状态更新不同的tabr
			// #ifdef APP-PLUS
			// this.initIM() //初始化极光
			plus.screen.lockOrientation('portrait-primary') //锁定竖屏
			setTimeout(() => {
				// if (!uni.getStorageSync('checkGpsOne')) {
				// 	this.checkGps()
				// }
				// this.checkGps()
				getDeviceInfo()
				APPUpdate()
			}, 20000)
			if (uni.getStorageSync('token')) {
			console.error(1112122222222)
				setTimeout(() => {
					if (!uni.getStorageSync('checkGpsOne')) {
							console.error(2122222222)
						this.checkGps()
					}
				}, 20000)
				this.uniPush()
			}
			// #endif
			// getAppList()
			this.start_task_remind_check() //开工播报
			uni.setStorageSync('isReboot', true)
			console.log('App Launch')
			if (uni.getStorageSync('token')) {
				// this.getCont()
				this.AppOpenExecuteOnce()
				if (uni.getStorageSync('userType') == 1) {
					this.getBox()
				}
			}
		},
		methods: {
			async AppOpenExecuteOnce() {
				let res = await this.$fetch(this.$api.get_app_first, {
					region: uni.getStorageSync('region') || 330372
				}, 'GET')
				if (res.code) return;
				console.log('res获取的是什么数据：', res);
				uni.setStorageSync('zhouchong', res.data.queryZhouChongFlag); // 周冲
				uni.setStorageSync('NewPeopleRedBag', res.data.queryNewEmployeeWhetherFloating); // 新人红包
				uni.setStorageSync('queryNewEmployeeWhether', res.data.queryNewEmployeeWhether); // 弹框 新雇员活动展示
				uni.setStorageSync('queryNewEmployeeAmount', res.data.queryNewEmployeeAmount); // 金额  新雇员活动展示
				uni.setStorageSync('showMask', res.data.popupsList); // 弹框
			},
			getBox() {
				this.$fetch(this.$api.query_bullet_box, {
					region: uni.getStorageSync('region') || 330372
				}, 'POST').then(res => {
					uni.setStorageSync('showMask', res.data)
				})
			},
			// 刷新列表重置定位缓存
			refreshLocation() {
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						uni.setStorageSync('taskListLocation', [res.latitude, res.longitude]);
						this.getAdcode(res.latitude, res.longitude)
						console.log("app加载时刷新列表重置定位", res.latitude, res.longitude);
					},
				})
			},
			closeZdyVoice() {
				this.isZdyV = 1
			},
			// 初始化数据库
			initDB() {
				console.log('启动数据库...')
				if (sqlite.isOpen()) {
					this.initTable()
				} else {
					sqlite.openSqlite().then(res => {
						this.initTable()
						console.log('数据库启动ok')
					}).catch(e => {
						console.log('启动数据库失败', e)
					})
				}
			},
			// 初始化数据库表
			initTable() {
				// sqlite.dropTable().then(() => {
				//   console.log('删除表成功')
				// }).catch(e => {
				//   console.log('删除表失败', e)
				// })
				sqlite.createTable().then(r => {
					console.log('数据库表打开ok!!' + r)
					this.initWsChat()
				}).catch(e => {
					console.log('数据库表打开失败!!' + e)
				})
			},
			initWsChat() {
				this.connectSocket()
				let heartbeat
				uni.onSocketOpen((res) => {
					heartbeat = setInterval(() => {
						// 发送心跳
						uni.sendSocketMessage({
							data: JSON.stringify({
								msgType: 0
							})
						});
					}, 60 * 1000 * 4)
				});
				uni.onSocketError((res) => {
					if (heartbeat) {
						clearInterval(heartbeat)
						heartbeat = null
					}
					// 循环重试连接
					setTimeout(() => {
						this.connectSocket()
					}, 5 * 1000)
				});
				// 接受到服务器的消息
				uni.onSocketMessage(res => {
					console.log('收到服务器内容：' + res.data);
					let tempXd = JSON.parse(res.data)?.data
					if (tempXd.msgType == 1) {
						uni.setStorageSync('isTabBarRed', true)
						uni.showTabBarRedDot({
							index: 2,
							success: (res) => {},
							fail: (err) => {}
						})
					}
					this.handleMsg(JSON.parse(res.data)?.data)
				});
			},
			handleMsg(msg) {
				if (Array.isArray(msg)) { // 离线消息
					msg.forEach(msgitem => {
						this.handleMsg(msgitem)
					})
					// 接收完毕向服务器发送回执
					uni.sendSocketMessage({
						data: JSON.stringify({
							msgType: 2
						})
					});
				} else {
					if (msg.msgType == 5) {
						// 异地登录
						uni.showModal({
							title: '提示',
							content: '您的账号在异地登录',
							success: async () => {
								this.exitApp()
							}
						})
					} else {
						//非自己的文本图片消息震动 并触发聊天窗口处理显示
						if (msg.fromId != this.myuid && (msg.msgType === 1 || msg.msgType === 4 || msg.msgType === 6)) {
							sqlite.insertMuser({
								userId: msg.fromId
							}).then(() => {
								sqlite.insertMsg(msg).then(res => {
									console.log('插入聊天数据成功,', res)
								}).catch(e => {
									console.log('插入聊天数据失败=.=b', e)
								})
								uni.$emit('newMsg', msg)
								uni.vibrateLong();
							}).catch(e => {
								console.log('插入聊天对象数据成功,', e)
							})
						} else if (msg.msgType === 7) {
							uni.$emit('newInvMsg', msg)
							// console.log('333333333'+JSON.stringify(msg))
							uni.setStorageSync('newInvMsg', msg)
							// uni.vibrateLong();
						} else if (msg.msgType === 8) {
							uni.$emit('closeWorking', {})
							uni.$emit('closeDaikgong', {})
							// console.log(JSON.stringify(msg))
							if (msg.msg == '0') {
								uni.$emit('closeWorking', {})
								uni.$emit('closeDaikgong', {})
								Voice('很抱歉，您接单的任务已取消')
							}
							this.start_task_remind_check(1)
						}
					}
				}
			},
			async exitApp() {
				await this.$fetch(this.$api.upd_user_detail, {
					cid: 0
				}, 'POST')
				uni.showToast({
					title: '已退出~',
					icon: 'none'
				})
				try {
					uni.removeStorageSync('userInfo');
					uni.removeStorageSync('token');
					uni.removeStorageSync('userType');
					uni.removeStorageSync('userId');
					uni.removeStorageSync('level');
					uni.removeStorageSync('first-is');
					uni.removeStorageSync('isHavePayPassword');
				} catch (e) {
					// error
				}
				uni.$emit('userLogin', {
					online: 0
				})
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/index/index'
					})
				}, 600)
			},
			connectSocket() {
				var url = baseURL.split(':');
				if (url[0] && url[0] === 'https') {
					url[0] = 'wss' // https协议换成wss
				} else {
					url[0] = 'ws' // http协议换成ws
				}
				uni.connectSocket({
					url: url.join(':') + 'websocket?token=' + Base64.encode('DLG_TOKEN_' + uni.getStorageSync(
						'token'))
				});
			},
			// 初始化极光
			initIM() {
				console.log('初始化极光')
				//极光聊天室二次封装
				const dcRichAlert = uni.requireNativePlugin('ZWM-BJXMapView')
				//极光初始化
				dcRichAlert.JmessageManagerInit({
					appKey: '6d3c21662373e17b01f9b169'
				}, result => { //没有返回值
				})
			},
			// 检测定位是否开启
			checkGps() {
				uni.setStorageSync('checkGpsOne', true)
				let system = uni.getSystemInfoSync(); // 获取系统信息
				if (system.platform == 'android') { // 判断平台
					var context = plus.android.importClass("android.content.Context");
					var locationManager = plus.android.importClass("android.location.LocationManager")
					var main = plus.android.runtimeMainActivity();
					var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
					if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
						uni.showModal({
							title: '提醒',
							content: '请开启定位',
							confirmText: '去开启',
							showCancel: false, // 不显示取消按钮
							success() {
								if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
									var Intent = plus.android.importClass('android.content.Intent');
									var Settings = plus.android.importClass('android.provider.Settings');
									var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
									main.startActivity(intent); // 打开系统设置定位服务页面
								}
							}
						})
					} else {
						console.log('Android定位功能已开启')
						this.requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION')
					}
				} else {
					// 苹果
					if (permission.judgeIosPermission("location")) { //判断iOS上是否给予位置权限，有权限返回true，否则返回false
						this.get_current_location()
						console.log('IOS定位功能已开启')
						// return
					} else {
						console.log('IOS定位功能没有开启')
						uni.showModal({
							title: '提醒',
							content: '请在权限管理中同意位置信息授权',
							confirmText: '去开启',
							// showCancel: false, // 不显示取消按钮
							success(res) {
								if (res.confirm) {
									permission.gotoAppPermissionSetting()
								}
							}
						})
					}
				}
			},
			// 判断用户是否授权定位
			async requestAndroidPermission(permisionID) {
				if (plus.os.name === 'Android') {
					console.error(112323322323)
					var result = await permission.requestAndroidPermission(permisionID)
					console.log('=========================',result)
					if (result === 1) {
						this.get_current_location()
						// console.log("Android定位功能已开启");
					} else {
						// 被永久拒绝权限
						uni.showModal({
							title: '提醒',
							content: '为您推荐或发布信息需要展示位置，请在权限管理中同意位置信息授权',
							confirmText: '去开启',
							// showCancel: false, // 不显示取消按钮
							success(res) {
								if (res.confirm) {
									permission.gotoAppPermissionSetting()
								}
							}
						})
					}
				}
			},
			// 获取用户当前的经纬度
			get_current_location() {
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						// console.log('获取经纬度~~ 10月20日')
						uni.setStorageSync('location', [res.latitude, res.longitude])
						this.getAdcode(res.latitude, res.longitude)
					}
				})
				setInterval(() => {
					uni.getLocation({
						type: 'gcj02',
						success: (res) => {
							console.log('setInterval获取经纬度~~')
							uni.setStorageSync('location', [res.latitude, res.longitude])
							this.getAdcode(res.latitude, res.longitude)
						}
					})
				}, 120000)
			},
			// 由经纬度查询街道的行政代码
			getAdcode(lat, lng) {
				uni.request({
					url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
					data: {
						key: '39fcf04d6c9deb64c8436b40445c829e',
						location: lng + ',' + lat
					},
					success: res => {
						uni.setStorageSync('currentAddress', res.data.regeocode.formatted_address)
						let region = res.data.regeocode.addressComponent.towncode.slice(0, 9)
						console.log(uni.getStorageSync('region'))
						uni.setStorageSync('region', region)
						uni.setStorageSync('region1', region)
						if (uni.getStorageSync('token')) {
							this.upd_user(lat, lng, region) ////更新用户位置
						}
					}
				})
			},
			// 开工提示校验，接单确认提醒
			async start_task_remind_check(num = null) {
				let that = this
				if (uni.getStorageSync('token') && uni.getStorageSync('userType') == 0) {
					//开工提示校验
					console.log('开工提示校验，接单确认提醒')
					let res = await that.$fetch(that.$api.start_task_remind_check, {}, 'POST')
					if (res.data == 1 && uni.getStorageSync('checked1')) {
						const player = new AudioPlayer('static/audio/ttsmaker-file-2023-7-8-14-34-30.mp3')
						player.play()
						// Voice('您已到开工地点，请尽快与雇主当面点击开工按钮')
					}
					// 接单确认提醒
					console.log('接单确认提醒~~~~~~~~~~', uni.getStorageSync('hasUnconfirm'), uni.getStorageSync('checked1'))
					if (uni.getStorageSync('hasUnconfirm') == 1 && uni.getStorageSync('checked1')) {
						if (uni.getStorageSync('OldStaff')) {
							Voice('这是老雇主的任务，可以直接接单哦')
						} else {
							// Voice('请尽快拨打电话与雇主确认订单')
						}
					} else if (uni.getStorageSync('hasUnconfirm') == 2 && uni.getStorageSync('checked1')) {
						Voice('请确认接单或取消订单')
					}
				}
				//等60s之后再开始循环
				this.workTimes = setInterval((async () => {
					if (uni.getStorageSync('token')) {
						//开工提示校验
						if (uni.getStorageSync('checked1')) {
							// console.log('开工提示校验，接单确认提醒')
							let res = await that.$fetch(that.$api.start_task_remind_check, {}, 'POST')
							// console.log(res.data)
							if (res.data == 1) {
								const player = new AudioPlayer(
									'static/audio/ttsmaker-file-2023-7-8-14-34-30.mp3')
								player.play()
								// Voice('您已到开工地点，请尽快与雇主当面点击开工按钮')
							}
							// 接单确认提醒
							console.log('接单确认提醒~~~~~~~~~~', uni.getStorageSync('hasUnconfirm'))
							if (uni.getStorageSync('hasUnconfirm') == 1) {
								if (uni.getStorageSync('OldStaff')) {
									Voice('这是老雇主的任务，可以直接接单哦。')
								} else {
									// Voice('请尽快拨打电话与雇主确认订单')
								}
							} else if (uni.getStorageSync('hasUnconfirm') == 2) {
								Voice('请确认接单或取消订单')
							}
							if (uni.getStorageSync('receivedTaskStartTime')) {
								let Minute = isResidueTimeByMinute(uni.getStorageSync(
									'receivedTaskStartTime'))
								if (Minute <= 30) {
									let resOpen = await that.$fetch(that.$api
									.get_order_status_is_open, {}, 'GET')
									console.log(resOpen);
									if (!resOpen.code && resOpen.data == 1) {
										if (num == 1) {
											Voice('')
										} else {
											Voice('您的工作马上要开始了，请不要迟到')
										}
									}
									if (Minute <= 2 || (!resOpen.code && resOpen.data == 0)) uni
										.setStorageSync('receivedTaskStartTime', '')
								}
							}
						}
					}
				}), 180000)
			},
			//更新用户位置
			async upd_user(lat, lng, region) {
				//经纬度保留6位小数
				lat = lat.toFixed(6)
				lng = lng.toFixed(6)
				region = region.slice(0, 9)
				console.log('更新用户位置', lat, lng, region)
				let res = await this.$fetch(this.$api.upd_user, {
					lat: lat,
					lng: lng,
					region: region
				}, 'POST')
				console.log('更新用户位置res', res)
			},
			// 获取当前时间和缓存时间(一天一次)
			get_nowTime(futrue) {
				// 执行这个存储的话就代表今日已展示过，今日不管什么时间段进入都不会执行以下代码
				let nowTime = new Date();
				let futrueTime;
				if (futrue) {
					futrueTime = new Date(futrue); // 缓存时间
				} else {
					// 没有的话就获取今天的时间
					futrueTime = new Date();
					// 缓存时间
					uni.setStorageSync('showNewTime', futrueTime);
				}
				// 当天日期 和 缓存前一天的日期做对比
				if (futrueTime && new Date(futrueTime).toDateString() === nowTime.toDateString()) {
					return false;
				} else {
					// 如果今日没有执行的话就给存储起来，今日就不会再执行了
					uni.setStorageSync('showNewTime', nowTime)
					return true;
				}
			},
			// 配置数据
			async handleData() {
				// console.log('app一进来有红点吗？', uni.getStorageSync('isTabBarRed'))
				// console.log('app里总体聊天',this.$store.state.isChatMsg,'平台消息',this.$store.state.isNewPlatMsg, '底部消息', this.$store.state.isTabBar)
				// 判断消息是否有红点
				if (this.$store.state.isChatMsg || this.$store.state.isNewPlatMsg || this.$store.state.isTabBar) {
					// 展示红点
					// uni.showTabBarRedDot({
					// 	index: 2,
					// 	success: (res) => {
					// 		console.log('app一进来有红点')
					// 	},
					// 	fail: (err) => {
					// 		// console.log('err', err)
					// 	}
					// })
				} else {
					uni.removeTabBarBadge({
						index: 2,
						success: (res) => {
							// console.log('成功')
						},
						fail: (err) => {
							// console.log('err', err)
						},
					})
				}
				// 雇员端筛选工作
				let screenObj = uni.getStorageSync('screenObj') ? uni.getStorageSync('screenObj') : {}
				let places = placeMap()
				screenObj.isAsc = 'desc'
				screenObj.taskType = ''
				screenObj.orderByColumn = ''
				screenObj.sex = ''
				screenObj.startReward = ''
				screenObj.endReward = ''
				screenObj.pageNum = 0
				screenObj.pageSize = 40
				screenObj.status = 3
				screenObj.region = uni.getStorageSync('region').slice(0, 6)
				if (!screenObj.region) {
					this.$store.commit('selectCityChange', places['330782'])
				} else {
					this.$store.commit('selectCityChange', places[screenObj.region])
				}
				uni.setStorageSync('screenObj', screenObj)
				//雇主端筛选雇员
				// let usersObj = uni.getStorageSync('usersObj')
				// usersObj.endAge = ''
				// usersObj.expectWorkType = ''
				// usersObj.isAsc = 'asc'
				// usersObj.orderByColumn = 'distance'
				// usersObj.pageNum = 0
				// usersObj.pageSize = 10
				// usersObj.sex = ''
				// usersObj.startAge = ''
				// usersObj.userJobStatus = ''
				// usersObj.userName = ''
				// usersObj.region = uni.getStorageSync('region').slice(0, 6)
				// uni.setStorageSync('usersObj', usersObj)
				// if (!usersObj.region) {
				// 	this.$store.commit('selectCityChange', places['330782'])
				// } else {
				// 	this.$store.commit('selectCityChange', places[usersObj.region])
				// }
				uni.setStorageSync('word', '') //将雇主端搜索关键字清空 
				let res4 = await get_property_list_by_type()
				//期望类型
				uni.setStorageSync('expect_type', res4.dlg_expect_type)
				// 期望工作时间
				uni.setStorageSync('workTime', res4.dlg_expect_workTime)
				// 街道 
				uni.setStorageSync('street', res4.dlg_street)
				// 期望工作类型
				uni.setStorageSync('work_type', res4.dlg_expect_work_type)
				// 意见反馈类型
				uni.setStorageSync('opinionType', res4.dlg_opinion_type)
				// 热门搜索
				uni.setStorageSync('hotList', res4.dlg_hot_search)
				//获取开放区域
				uni.setStorageSync('Openarea', res4.adcode)
				uni.setStorageSync('UUID', res4.applet_id)
				// 平台提示
				uni.setStorageSync('platform_prompt', res4.platform_prompt)
				// 核算开关 1开 0关
				uni.setStorageSync('nucleic_acid_require', res4.nucleic_acid_require)
				// 获取图片路径
				uni.setStorageSync('imgPath', res4.pic_url)
				// 发布任务时 缴纳保证金配置(元/人)
				uni.setStorageSync('bond', res4.bond)
				// 雇员取消x小时内不可接单
				uni.setStorageSync('x_hours_no_order', res4.x_hours_no_order)
				// 雇员取消订单扣除诚信值
				uni.setStorageSync('order_user_cancel_cut_integrity', res4.order_user_cancel_cut_integrity)
				// 雇主取消任务扣除诚信值
				uni.setStorageSync('task_user_cancel_cut_integrity', res4.task_user_cancel_cut_integrity)
				// 实名认证诚信值配置
				uni.setStorageSync('real_auth_integrity', res4.real_auth_integrity)
				// 客服电话
				uni.setStorageSync('serviceTelephone', res4.telephone)
				//收取雇员百分之4手续费
				uni.setStorageSync('user_amount_ratio', res4.user_amount_ratio)
				// x分钟自动确认开工配置
				uni.setStorageSync('x_minute_auto_confirm', res4.x_minute_auto_confirm)
				//接单超时取消 单位 分钟 整数
				uni.setStorageSync('overtime_cancel', res4.overtime_cancel)
				// 手机音量
				uni.setStorageSync('app_volume', res4.app_volume)
				this.app_volume = res4.app_volume
				if (new Date().toISOString().slice(0, 10) != uni.getStorageSync('date')) {
					try {
						uni.removeStorageSync('heEvaluateLv');
					} catch (e) {
						// error
					}
				}
				if (!uni.getStorageSync('isHavePayPassword')) {
					let isHavePayPassword = await this.$fetch(this.$api.v1_Buy_monthly_card, {
						cardId: 0,
						payType: 2,
						payPwd: '1'
					}, 'POST')
					if (isHavePayPassword.msg == "获取不到当前用户支付密码,请先设置") {
						uni.setStorageSync("isHavePayPassword", false)
					} else {
						uni.setStorageSync("isHavePayPassword", true)
					}
				}
				// #ifdef APP-PLUS
				this.get_volume() //音量设置
				// #endif
			},
			//监听音量
			get_volume() {
				// console.log('初始音量', plus.device.getVolume())
				plus.key.addEventListener("volumeupbutton", function(e) {
					console.log('监听音量', plus.device.getVolume())
				})
				plus.key.addEventListener("volumedownbutton", function(e) {
					console.log('监听音量', plus.device.getVolume())
				})
				if (plus.device.getVolume() < this.app_volume) {
					plus.device.setVolume(this.app_volume)
					console.log('修改后音量', plus.device.getVolume())
				}
			},
			// 推送
			uniPush() {
				var pinf = plus.push.getClientInfo();
				var cid = pinf.clientid; //客户端标识  
				console.log('推送cid：', cid)
				// 获取推送服务提供商
				uni.getProvider({
					service: 'push',
					success: (res) => {
						console.log('获取推送服务提供商：', res)
					}
				})
				let that = this
				// 监听系统通知栏
				plus.push.addEventListener('click', function(msg) {
					console.log('推送系统通知栏111111：', msg.title)
					if (msg.content.includes('-ORDER-')) {
						let id = msg.content.toString()
						id = id.split('-ORDER-')[1]
						if (uni.getStorageSync('userType') == 1) {
							that.$store.commit('isNewPlatMsgChange', true)
							uni.navigateTo({
								url: '/pages/app-employer/boss-order-detail/boss-order-detail?id=' + id
							})
						} else {
							uni.navigateTo({
								url: '/pages/order-detail/order-detail?id=' + id
							})
						}
					}
					/* console.log('推送系统通知栏2：',JSON.parse(msg.payload))
					console.log('推送系统通知栏2：',JSON.parse(msg.payload).message) */
					// 点击弹框取消红点
					if (JSON.parse(msg.payload).message == '附近有刚发布的零工,请及时查看!' || JSON.parse(msg.payload).title ==
						'零工推送通知') {
						console.log('零工推送--去首页')
						uni.switchTab({
							url: '/pages/index/index'
						})
					} else {
						console.log('零工推送--平台消息')
						uni.navigateTo({
							url: '/pages/platform-message/platform-message'
						})
					}
					// ios 离线接收到的透传消息会出现在系统通知栏中，点击之后会触发点击回调。
					// 应用处于在线状态时，不会自动创建系统通知栏，需要本地生成。
					// 安卓离线之后，通过透传生成的系统通知栏点击之后无法触发回调，但是本地生成的可以，ios离线透传消息点击通知栏可以触发点击回调。
				}, false)
				//监听接收透传消息事件  
				plus.push.addEventListener('receive', function(msg) {
					// 语音是否开启
					let checked1 = uni.getStorageSync('checked1')
					checked1 = checked1 === '' ? true : checked1
					uni.setStorageSync('checked1', checked1)
					console.log('是否语音2', uni.getStorageSync('checked1'))
					console.log('这是一条透传消息222222：', msg)
					if (msg.title == '有一位雇员接取了您的任务!') {
						uni.setStorageSync('isReceiveBarRed', false)
						uni.setStorageSync('isTabBarRed', true)
						if (uni.getStorageSync('checked1')) {
							Voice(msg.title)
						}
					}
					if (msg.title == '您有一位雇员收工了') {
						uni.setStorageSync('isknockoffBarRed', false)
						uni.setStorageSync('isTabBarRed', true)
						if (uni.getStorageSync('checked1')) {
							Voice('您有一位雇员已收工，记得结算薪酬')
						}
					}
					// uni.setStorageSync('isTabBarRed', true)
					var pages = getCurrentPages() // 获取栈实例
					var page = pages[pages.length - 1]
					if (page.route == 'pages/index/index') {
						if (msg.content.includes('-ORDER-')) {
							uni.navigateTo({
								url: '/pages/order-detail/order-detail?id=' + msg.payload.titleText.split(
									'-ORDER-')[1]
							})
						}
						page.$vm.onRefresh()
					}
					//处理透传消息的业务逻辑代码
					let platform = uni.getSystemInfoSync().platform
					var payload
					if (platform == 'android') {
						payload = msg.payload
						//payload = JSON.parse(msg.payload)
						var messageTitle = payload.title
						var messageContent = payload.titleText
						plus.push.createMessage(messageContent)
						console.log('创建消息安卓', messageContent, typeof messageContent)
						if (messageTitle == '雇主已拒绝您的开工申请') {
							if (uni.getStorageSync('checked1')) {
								Voice(messageTitle)
							}
							uni.$emit('closeKgR', {})
						}
						if (messageTitle == '雇主已同意您的开工申请') {
							if (uni.getStorageSync('checked1')) {
								Voice(messageTitle)
							}
							uni.$emit('closeKgR', {})
						}
						if (messageTitle == '有雇员申请了开工，如在15分钟内没有处理，系统将自动同意。') {
							if (uni.getStorageSync('checked1')) {
								Voice(messageTitle)
							}
							uni.$emit('closeKgR', {})
						}
						if (uni.getStorageSync('checked1')) {
							if (messageTitle == '零工审核通知') {
								Voice(messageContent)
							} else if (messageTitle == '零工推送通知') {
								console.log('安卓声音-零工推送通知', payload)
								Voice(messageContent)
							} else if (messageTitle == '雇主结算你的订单') {
								console.log('雇主结算你的订单')
								Voice(messageContent)
							} else if (messageTitle == '雇主取消了你的订单') {
								console.log('雇主取消了你的订单')
								Voice(messageContent)
							} else {
								console.log('安卓声音-其他')
								Voice(messageTitle)
							}
						}
					} else {
						/**
						 * 对 ios 数据格式整理发现，当透传为离线状态时；msg 中的 aps 是有数据的，且type 为 receive
						 * 当透传消息为在线时，aps 为 null, type 同样为 receive
						 * 当状态通知栏为本地创建时，aps 为 null, 且没有 type 属性
						 */
						payload = msg.payload;
						if (msg.aps == null && msg.type == "receive") {
							var messageTitle = payload.title;
							var messageContent = payload.titleText;
							//创建本地消息,发送的本地消息也会被receive方法接收到，但没有type属性，且aps是null  
							plus.push.createMessage(messageContent, JSON.stringify(payload), {
								title: messageTitle
							});
							console.log('创建消息苹果', messageTitle, messageContent)
							if (messageTitle == '雇主已拒绝您的开工申请') {
								if (uni.getStorageSync('checked1')) {
									Voice(messageTitle)
								}
								uni.$emit('closeKgR', {})
							}
							if (messageTitle == '雇主已同意您的开工申请') {
								if (uni.getStorageSync('checked1')) {
									Voice(messageTitle)
								}
								uni.$emit('closeKgR', {})
							}
							if (messageTitle == '有雇员申请了开工，如在15分钟内没有处理，系统将自动同意。') {
								if (uni.getStorageSync('checked1')) {
									Voice(messageTitle)
								}
								uni.$emit('closeKgR', {})
							}
							if (uni.getStorageSync('checked1')) {
								if (messageTitle == '零工审核通知') {
									Voice(messageContent)
								} else if (messageTitle == '零工推送通知') {
									console.log('苹果声音-零工推送通知')
									Voice(messageContent)
								} else {
									console.log('苹果声音-其他', )
									Voice(messageTitle)
								}
							}
						}
					}
					// 如果是订单结算消息，弹出完成弹框
					if (messageTitle == '很抱歉，您接单的任务已取消') {
						if (uni.getStorageSync('checked1')) {
							Voice(messageTitle)
						}
						uni.$emit('closeWorking', {})
						uni.$emit('closeDaikgong', {})
					}
					if (messageTitle == '雇主结算您的接单') {
						that.$store.commit('isFinishModalChange', false)
					}
					if (messageContent == '附近有新的零工任务，请注意查看!') {
						if (uni.getStorageSync('checked1')) {
							Voice(messageContent)
						}
					}
					if (messageContent != '附近有新的零工任务，请注意查看!') {
						// 平台消息上显示红点
						that.$store.commit('isNewPlatMsgChange', true)
						// 消息导航栏有红点
						that.$store.commit('isTabBarChange', false)
					}
				}, false);
			},
			// 切换底部导航栏
			setTabr() {
				if (!uni.getStorageSync('token')) {
					uni.setStorageSync('userType', 0)
				}
				if (uni.getStorageSync('userType') == 1) {
					// setTimeout(() => {
					// 	uni.setTabBarItem({
					// 		index: 0,
					// 		text: '雇员',
					// 		iconPath: 'static/tab-bar/9.png',
					// 		selectedIconPath: 'static/tab-bar/10.png'
					// 	})
					// 	uni.setTabBarItem({
					// 		index: 1,
					// 		text: '发布',
					// 		iconPath: 'static/tab-bar/11.png',
					// 		selectedIconPath: 'static/tab-bar/12.png',
					// 	})
					// }, 2000)
					uni.hideTabBar()
				} else {
					setTimeout(() => {
						uni.setTabBarItem({
							index: 0,
							text: '零工',
							"iconPath": "static/tab-bar/1.png",
							"selectedIconPath": "static/tab-bar/2.png",
						})
						uni.setTabBarItem({
							index: 1,
							text: '接单',
							"iconPath": "static/tab-bar/3.png",
							"selectedIconPath": "static/tab-bar/4.png",
						})
					}, 2000)
				}
			},
			dateFormat(fmt, date) {
				let ret;
				const opt = {
					"Y+": date.getFullYear().toString(), // 年
					"m+": (date.getMonth() + 1).toString(), // 月
					"d+": date.getDate().toString(), // 日
					"H+": date.getHours().toString(), // 时
					"M+": date.getMinutes().toString(), // 分
					"S+": date.getSeconds().toString() // 秒
					// 有其他格式化字符需求可以继续添加，必须转化成字符串
				};
				for (let k in opt) {
					ret = new RegExp("(" + k + ")").exec(fmt);
					if (ret) {
						fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
					};
				};
				return fmt;
			},
			async errorSubmit(userid, errmsg, phoneInfo, page) {
				let date = new Date()
				date = this.dateFormat("YYYY-mm-dd HH:MM:SS", date)
				let error = {
					userid: userid,
					url: page,
					phoneuser: phoneInfo,
					errmsg: errmsg,
					create_time: date,
					update_time: date
				}
				console.log(date)
				let res = await this.$fetch(this.$api.app_logerrmsg, error, 'POST', 'JSON')
				if (res.code) return uni.showToast({
					title: res.msg,
					icon: 'none'
				})
				console.log('err' + res)
				// uni.showToast({
				// 	title: '提交成功~',
				// 	icon: 'none'
				// })
			},
		},
		onShow: function() {
			// #ifdef APP-PLUS
			if (uni.getStorageSync('iswxzf') == 'true') {
				console.log('接收小程序参数', plus.runtime.arguments)
				// uni.setStorageSync('tempTrade', plus.runtime.arguments)
			}
			// #endif
		},
		onHide: function() {
			// console.log('App Hide')
			uni.setStorageSync('isReboot', false)
		},
		onError: function(e) {
			//this.errorSubmit('系统错误返回'+e)
			let errorINfoList = []
			if (uni.getStorageSync('errorInfo')) {
				errorINfoList = uni.getStorageSync('errorInfo')
			}
			// console.log('系统错误信息:')
			console.log(e.toString())
			// console.log('用户id' + uni.getStorageSync('userId'))
			var pages = getCurrentPages()
			let p = ''
			let errorINfo = e.toString()
			if (pages.length != 0) {
				p = '当前页面:' + pages[pages.length - 1].route + ':完整路由--'
				pages.forEach(v => {
					p += v.route + '----分割线-----'
				})
				console.log(p)
			} else {
				p = '未获取到'
			}
			errorINfo = errorINfo + '--' + p
			// #ifdef APP-PLUS
			// let phone = ''
			let phone = '手机型号' + "Model: " + plus.device.model + "--Vendor: " + plus.device.vendor
			//获取设备的型号
			// console.log("Model: " + plus.device.model);
			//获取设备的生产厂商
			// console.log("Vendor: " + plus.device.vendor);
			plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
				phone += '版本号' + wgtinfo.version
			})
			if (!errorINfoList.includes(errorINfo)) {
				this.errorSubmit(uni.getStorageSync('userId'), e.toString(), phone, p)
				errorINfoList.push(errorINfo)
				uni.setStorageSync('errorInfo', errorINfoList)
			}
			// #endif
			//app_logerrmsg
		},
	}
</script>
<style lang="scss">
	// #ifndef APP-NVUE
	@import "uview-ui/index.scss";
	// @import "@/uni_modules/uviewui-v1/index.scss";
	// #endif
</style>
<style>
	/* #ifdef H5 */
	checkbox .uni-checkbox-input {
		border-radius: 50%;
		/* border: 1px solid #FFCC33; */
	}

	checkbox .uni-checkbox-input.uni-checkbox-input-checked {
		border-radius: 50%;
		/* border: 1px solid #FFCC33; */
	}

	checkbox .uni-checkbox-input.uni-checkbox-input-checked::before {
		border-radius: 50%;
		/* border: 1px solid #FFCC33; */
	}

	/* #endif */
	/* #ifndef APP-PLUS-NVUE */
	page {
		background-color: #F2F2F2;
		color: #402110;
		font-size: 14px;
		font-family: PingFangSC-Regular;
	}

	.hg-30 {
		height: 30rpx;
		background: #F2F2F2;
	}

	.hg-98 {
		height: 98rpx;
		background: #F2F2F2;
	}

	.hg-108 {
		height: 108rpx;
		background: #F2F2F2;
	}

	.hg-128 {
		height: 128rpx;
		background: #F2F2F2;
	}

	.status-bar {
		height: calc(var(--status-bar-height) + 20rpx);
		background-color: #FFFFFF;
	}

	input {
		font-size: 14px;
	}

	.right-arrow {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.right-arrow::after {
		content: "";
		width: 15upx;
		height: 15upx;
		border-top: 4upx solid #ccc;
		border-right: 4upx solid #ccc;
		transform: rotate(45deg);
	}

	uni-checkbox .uni-checkbox-input {
		width: 24rpx !important;
		height: 24rpx !important;
		margin-bottom: 4rpx;
		border-radius: 50% !important;
	}

	/* #endif */
</style>